<script setup lang="ts">
import { computed, defineAsyncComponent, onBeforeMount, ref, unref } from 'vue'
import { useBaseApi } from '@/api/base'
import { useRoute } from 'vue-router'
import mittBus from '@/utils/mitt'
import type { VxeGridEvents, VxeToolbarProps } from 'vxe-table'
import type {
  BusinessUIAction,
  BusinessUIFormType,
  BusinessUIQueryType,
  BusinessUITableType,
  DicType,
  WorkflowDesignRow
} from '@/types/custom'

import TemplateVxeGrid from '@/views/components/grid/components/TemplateVxeGrid.vue'
import { getFormatValues } from '@/utils/custom'

const TemplateGrid = defineAsyncComponent(() => import('@/views/components/grid/TemplateGrid.vue'))

interface Props {
  disabled?: boolean
  params?: TypedAny
  insert?: boolean
  boxShadow?: boolean
  ready?: (value: number) => void
}

// a68e0bb5-7a93-4750-9689-d2197dc957e2
const route = useRoute()

const props = withDefaults(defineProps<Props>(), {
  insert: true
})

const emit = defineEmits(['fetch', 'close'])

const modelValue = defineModel<string>()

const { get_business_ui } = useBaseApi()

// 加载
const loading = ref(false)
// 查询栏
const uiQuery = ref<BusinessUIQueryType | undefined>()
// 表格
const uiTable = ref<BusinessUITableType | undefined>()
// 表单
const uiForm = ref<BusinessUIFormType | undefined>()
// 表单字典
const dicTable = ref<DicType[]>([])
// 查询字典
const dicQuery = ref<DicType[]>([])
// 按钮配置
const uiActions = ref<BusinessUIAction[]>([])
// 关联流程
const wfDesign = ref<WorkflowDesignRow | undefined>()
// 表格
const gridRef = ref()
// 工具栏配置
const toolbarConfig = ref<VxeToolbarProps>({})
// 子级表
const childrenRefs = ref()

// 子级表
const children = computed(() => uiTable.value?.children || [])

const isLayoutPadding = computed(() => {
  const h = uiTable.value?.default_value_parse.height || 0
  return children.value.reduce((a, b) => a + (b.height || 0), h) <= 100
})

const emptyText = computed(() => {
  return uiTable.value?.default_value_parse.emptyText || '暂无数据'
})

/**
 * 初始化mitt事件
 */
const onEventMitt = () => {
  if (uiTable.value && ['sys_workflow_list', 'sys_user_msg'].includes(uiTable.value.id)) {
    mittBus.on('onUpdateMsg', () => {
      onFetch()
    })
  }
}

/**
 * 格式化默认参数
 */
const onDefaultFetch = async () => {
  const id = unref(modelValue)
  if (!id) return
  loading.value = true
  return get_business_ui(id, true)
    .then(({ data }) => {
      const dic_table = data.dic_table || []
      const dic_query = data.dic_query || []
      const ui_table = data.ui_table
      const ui_query = data.ui_query
      const ui_form = data.ui_form
      const ui_actions = props.disabled ? [] : data.actions || []
      const wf_design = data.wf_design
      if (ui_table) {
        const { default_value_parse } = ui_table
        if (default_value_parse.toolbarConfig)
          toolbarConfig.value = default_value_parse.toolbarConfig
      }

      if (ui_table) {
        // 测试
        // if (!ui_table.children) {
        //   ui_table.children = [
        //     {
        //       id: '',
        //       title: '门店用户',
        //       height: 0,
        //       business_id: 'a68e0bb5-7a93-4750-9689-d2197dc957e2',
        //       default_value: '',
        //       default_value_parse: { store_id: '' }
        //     }
        //   ]
        // }
        uiTable.value = ui_table
      }
      if (ui_query) uiQuery.value = ui_query
      if (ui_form) uiForm.value = ui_form

      dicQuery.value = dic_query
      dicTable.value = dic_table
      wfDesign.value = wf_design
      uiActions.value = ui_actions
      onEventMitt()
    })
    .finally(() => (loading.value = false))
}

const onFetch = () => {
  gridRef.value?.onFetch()
}

const onRadioChange: VxeGridEvents.RadioChange<TypedAny> = ({ row }) => {
  const refGrids = unref(childrenRefs)
  if (refGrids.length) {
    refGrids.forEach((v: any) => {
      if (v.uiTable) {
        const child = uiTable.value?.children?.find((f) => f.business_id === v.uiTable.id)
        if (child) {
          for (const key in child.default_value_parse) {
            const value = getFormatValues(child.default_value_parse[key])
            child.default_value_parse[key] = row[key] || value
          }
        }
      }
      v.onFetch()
    })
  }
}

const getHeight = (rh?: number) => {
  const h = rh || 0
  return h ? (h <= 100 ? `${h}%` : `${h}px`) : 'none'
}

onBeforeMount(() => {
  if (route.query.id) {
    modelValue.value = String(route.query.id)
  } else if (!modelValue.value) modelValue.value = String(route.meta.id)
  onDefaultFetch()
})

defineExpose({ onFetch, gridRef })
</script>

<template>
  <div :class="{ 'layout-padding': isLayoutPadding }">
    <TemplateVxeGrid
      ref="gridRef"
      v-model="loading"
      :params="params"
      :toolbar-config="toolbarConfig"
      :ui-form="uiForm"
      :ui-table="uiTable"
      :ui-query="uiQuery"
      :dic-query="dicQuery"
      :dic-table="dicTable"
      :ui-actions="uiActions"
      :wf-design="wfDesign"
      :box-shadow="boxShadow"
      :disabled="disabled"
      :insert="insert"
      :ready="ready"
      :empty-text="emptyText"
      @close="emit('close', $event)"
      @fetch="emit('fetch', $event)"
      @radio-change="onRadioChange"
      :style="{ height: getHeight(uiTable?.default_value_parse.height) }"
    />
    <div
      v-for="(item, index) in children"
      :key="index"
      class="base-bg-color"
      :style="{ height: getHeight(item.height) }"
    >
      <div class="grid-group-title font16 mx5">{{ item.title }}</div>
      <TemplateGrid
        ref="childrenRefs"
        :box-shadow="false"
        :params="item.default_value_parse"
        :height="item.height"
        :insert="insert"
        v-model="item.business_id"
      />
    </div>
  </div>
</template>

<style scoped lang="scss">
.grid-group-title {
  position: relative;
  padding: 5px 5px 5px 10px;

  &::after {
    content: '';
    position: absolute;
    left: 0;
    top: 5px;
    bottom: 5px;
    width: 3px;
    background-color: var(--el-color-primary);
  }
}
</style>
